package com.jing.forum.controller;

import com.jing.forum.common.AppResult;
import com.jing.forum.common.ResultCode;
import com.jing.forum.config.AppConfig;
import com.jing.forum.model.Article;
import com.jing.forum.model.Board;
import com.jing.forum.model.User;
import com.jing.forum.services.IArticleService;
import com.jing.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "文章接口")
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 发布新帖子
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 校验用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 版块的内容
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            // 返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        // 封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        // 调用Service
        articleService.create(article);
        // 响应
        return AppResult.success();
    }

    /**
     *
     * @param boardId
     * @return
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllBoardId(@ApiParam("版块id") @RequestParam(value = "boardId",required = false)
                                                          Long boardId) {

        // 定义返回结果集
        List<Article> articles;
        if (boardId == null) {
            // 查询所有帖子
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if (articles == null) {
            // 如果结果集为空,就创建一个空集合
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }


    @ApiOperation("根据帖子ID获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails ( HttpServletRequest request,
                        @ApiParam("id") @RequestParam("id") @NonNull Long id) {
        // 从session 中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用service 获取帖子详情
        Article article = articleService.selectDetailById(id);
        // 判断结果是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断当前用户是否为作者
        if (user.getId() == article.getUserId()) {
            // 标识为作者
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify (HttpServletRequest request,
                             @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id,
                             @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (!user.getId().equals(article.getUserId())) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖子的状态 - 已归档
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 调用Service
        articleService.modify(id, title, content);
        // 打印日志
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");
        // 返回正确的结果
        return AppResult.success();
    }


    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            // 返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用service
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 表示用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 校验当前登录的用户是不是作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用Service
        articleService.deleteById(id);
        // 返回操作成功
        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId) {
        // 如果UserId 为空 , 那么从session中获取当前登录的用户id
        if (userId == null) {
            // 获取session
            HttpSession session = request.getSession(false);
            // 获取User 对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }

    /**
     * 帖子分页
     * @param
     * @param
     * @return
     */
//    @ApiOperation("分页查询")
//    @GetMapping("/getlistbypage")
//    public AppResult getListByPage(
//            @ApiParam("页码") @RequestParam("pindex") @NonNull Integer pindex,
//            @ApiParam("每条显示条数") @RequestParam("psize") @NonNull Integer psize) throws ExecutionException, InterruptedException {
//        // 1.参数矫正
//        if (pindex == null || pindex < 1) {
//            pindex = 1; // 参数矫正
//        }
//        if (psize == null || psize < 1) {
//            psize = 10;// 参数矫正
//        }
//        // 2.并发进行文章列表和总页数查询
//        // 2.1 查询分页列表数据
//        int finalOffset = psize *(pindex -1); // 分页公式
//        int finalPSize = psize;
//        FutureTask<List<Article>> listTask = new FutureTask<>(()->{
//            return articleService.getListByPage(finalPSize,finalOffset);
//        });
//        // 2.2 查找总页数
//        FutureTask<Integer> sizeTask = new FutureTask<>(()->{
//            // 总条数
//            int totalCount = articleService.getCount();
//            double sizeTemp = (totalCount*1.0) / (finalPSize*1.0);
//            return (int)Math.ceil(sizeTemp);
//        });
//        taskExecutor.submit(listTask);
//        taskExecutor.submit(sizeTask);
//        // 3.组装数据
//        List<Article> list = listTask.get();
//        int size = sizeTask.get();
//        HashMap<String,Object> map = new HashMap<>();
//        map.put("list",list);
//        map.put("size",size);
//        // 4.将结果返回个给前端
//        return AppResult.success(map);
//    }
//    public String index(Model model, ArticleQuery articleQuery) {
//        PageInfo<Article> articlePageInfo = articleService.listArticle(articleQuery);
//        model.addAttribute("page",articlePageInfo);
//        return "index";
//    }



}
